// pages/diy/diy.js
const API = require('../../utils/api.js'); // 引入封装好的 API 方法
Page({
  data: {
    searchKeyword: '',
    recipes: [],
    loading: false,
    showModal: false,
    selectedRecipe: null,
    hasMore: true,
    isDarkMode: false
  },
  onLoad(options) {
    // 加载暗黑模式状态
    this.setData({
      isDarkMode: wx.getStorageSync('isDarkMode') || false
    });
    // 设置页面样式
    if (this.data.isDarkMode) {
      wx.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#1a1a1a'
      });
    }
  },

  // 监听输入变化
  onInputChange(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 清除搜索内容
  clearSearch() {
    this.setData({
      searchKeyword: '',
    });
  },

  // 搜索按钮点击
  onSearch() {
    if (!this.data.searchKeyword.trim()) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }
    this.searchRecipes();
  },

  // 搜索菜谱
  async searchRecipes() {
    this.setData({ loading: true });
    console.log(this.data.searchKeyword)
    let cookList = await API.cookQuery(this.data.searchKeyword)
    
    this.setData({
      recipes: cookList,
      loading: false,
    });
  },





  // 菜谱卡片点击
  onRecipeClick(e) {
    const recipeId = e.currentTarget.dataset.id;
    const recipe = this.data.recipes.find(r => r.id === recipeId);
    
    if (recipe) {
      this.setData({
        selectedRecipe: recipe,
        showModal: true
      });
    }
  },

  // 关闭模态框
  onCloseModal() {
    this.setData({
      showModal: false,
      selectedRecipe: null
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.searchKeyword) {
      this.searchRecipes();
    }
    wx.stopPullDownRefresh();
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.searchRecipes(this.data.searchKeyword, this.data.page + 1);
    }
  },



  // 监听暗黑模式变化
  onShow() {
    const isDarkMode = wx.getStorageSync('isDarkMode') || false;
    if (isDarkMode !== this.data.isDarkMode) {
      this.setData({ isDarkMode });
      if (isDarkMode) {
        wx.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: '#1a1a1a'
        });
      } else {
        wx.setNavigationBarColor({
          frontColor: '#000000',
          backgroundColor: '#ffffff'
        });
      }
    }
  }
})